package com.iqilu.ksd.activity.live;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.BaseActivity;
import com.iqilu.ksd.activity.LiveVideoActivity;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.FileUtils;
import com.iqilu.ksd.utils.KeyboardUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Coofee on 2016/11/24.
 */

public class VideoActivity extends BaseActivity {

    private static final String TAG = "VideoActivity";

    private int id;
    private String videoPath;
    private String thumbpath;
    private LigDialog ligDialog;

    private Button btCancel;
    private Button btSend;
    private EditText etEmoji;
    private RelativeLayout layPic;
    private RelativeLayout layVideo;
    private ImageView imgThumb;
    private ImageView imgCover;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_view_common);
        initView();
        id = getIntent().getIntExtra("id", 0);
        videoPath = getIntent().getStringExtra("videoPath");
        thumbpath = getIntent().getStringExtra("thumbpath");
        imgThumb.setImageURI(Uri.parse("file://" + thumbpath));
        layPic.setVisibility(View.VISIBLE);
        layVideo.setVisibility(View.VISIBLE);
    }

    private void initView() {
        btCancel = getView(R.id.bt_cancel);
        btSend = getView(R.id.bt_send);
        etEmoji = getView(R.id.et_emoji);
        layPic = getView(R.id.lay_pic);
        layVideo = getView(R.id.lay_video);
        imgThumb = getView(R.id.img_thumb);
        imgCover = getView(R.id.img_cover);
        layVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                play();
            }
        });
        btCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addVideo2();
//                cutFile();
            }
        });
    }

    private void play() {
        Intent intent = new Intent(this, LiveVideoActivity.class);
        intent.putExtra("url", "file://" + videoPath);
        startActivity(intent);
    }

    private void cutFile() {
        int count = 0;
        int index = 0;
        int percent = 500 * 1024;
        String tempPath;
        File file = new File(videoPath);
        FileUtils.createOrExistsDir(CacheUtils.getCompressDir(this));
        tempPath = CacheUtils.getCompressDir(this) + file.getName();
        count = (int) Math.ceil((float) file.length() / percent);
        Log.i(TAG, "length==>" + file.length());
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(videoPath, "r");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < count; i++) {
            byte[] buf;
            File tempFile = new File(tempPath);
            if (i == count - 1) {
                int leftLength = (int) (file.length() - percent * i);
                buf = new byte[leftLength];
            } else {
                buf = new byte[percent];
            }
            try {
                randomAccessFile.seek(i * percent);
                randomAccessFile.read(buf);
                OutputStream output = new FileOutputStream(tempFile);
                BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
                bufferedOutput.write(buf);
                bufferedOutput.flush();
                output.close();
                bufferedOutput.close();
                Log.i(TAG, "cutFile length===>" + tempFile.length() + ";path=======>" + tempFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            randomAccessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 临时解决方案
     * 创建一个新的OkHttp，超时设置为600s
     */
    private void addVideo2() {
        String url = Api.URL_LIVE_VIDEO;
        String description = Uri.encode(etEmoji.getText().toString());
        File videoFile = new File(videoPath);
        File thumbFile = new File(thumbpath);
        Log.i(TAG, "thumbpath=>" + thumbpath);
        ClearableCookieJar cookieJar = ((MyApplication) getApplication()).getCookieJar();
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(600, TimeUnit.SECONDS)
                .cookieJar(cookieJar)
                .build();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("filedata[]", videoFile.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), videoFile))
                .addFormDataPart("filedata[]", thumbFile.getName(), RequestBody.create(MediaType.parse("image/jpeg"), thumbFile))
                .addFormDataPart("liveid", "" + id)
                .addFormDataPart("description", "" + description)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Call call = mOkHttpClient.newCall(request);
        ligDialog = new LigDialog(VideoActivity.this, getString(R.string.live_upload_video));
        ligDialog.show();
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        uploadResult("");
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            uploadResult(response.body().string());
                        } catch (IOException e) {
                            uploadResult("");
                        }
                    }
                });
            }
        });
    }

    private void uploadResult(String response) {
        Log.i(TAG, "response=====>" + response);
        ligDialog.dismiss();
        int result = 0;
        try {
            JSONObject jsonObject = new JSONObject(response);
            result = jsonObject.getInt("status");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (result == 1) {
            Toast.makeText(VideoActivity.this, R.string.live_addvideo_success, Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(VideoActivity.this, R.string.live_addvideo_fail, Toast.LENGTH_SHORT).show();
        }
    }

    private void addVideo() {
        String url = Api.URL_LIVE_VIDEO;
        String description = Uri.encode(etEmoji.getText().toString());
        File videoFile = new File(videoPath);
        File thumbFile = new File(thumbpath);
        OkHttpUtils
                .post()
                .url(url)
                .addParams("liveid", "" + id)
                .addParams("description", "" + description)
                .addFile("filedata[]", "" + videoFile.getName(), videoFile)
                .addFile("filedata[]", "" + thumbFile.getName(), thumbFile)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        ligDialog = new LigDialog(VideoActivity.this, getString(R.string.live_upload_video));
                        ligDialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ligDialog.dismiss();
                        Log.i(TAG, "err===>" + e.toString());
                        Toast.makeText(VideoActivity.this, R.string.live_addvideo_fail, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i(TAG, "response=" + response);
                        ligDialog.dismiss();
                        int result = 0;
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            result = jsonObject.getInt("status");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (result == 1) {
                            Toast.makeText(VideoActivity.this, R.string.live_addvideo_success, Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(VideoActivity.this, R.string.live_addvideo_fail, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}